package com.computer.mvcframework.servlet;

import com.computer.spring.framework.annotation.BYRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Description
 * @Author MagicIce
 * @Date 2020/11/12 17:17
 */
public class Handler {

    /**
     * 保存方法对应的实例
     * 保存映射的方法
     * 匹配规则
     * 参数顺序
     */
    protected Object controller;
    protected Method method;
    protected Pattern pattern;
    protected Map<String, Integer> paramIndexMapping;

    public Handler(Object controller, Method method, Pattern pattern) {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        paramIndexMapping = new HashMap<>();
        putParamIndexMapping(method);
    }

    private void putParamIndexMapping(Method method) {

        //  提取方法中加了注解的参数
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            for (Annotation annotation : annotations[i]) {
                if (annotation instanceof BYRequestParam) {
                    String paramName = ((BYRequestParam) annotation).value();
                    if (!"".equals(paramName.trim())){
                        paramIndexMapping.put(paramName, i);
                    }
                }
            }
        }

        //  提取方法中的 request 和 response 参数
        Class<?>[] paramsTypes = method.getParameterTypes();
        for (int i = 0; i < paramsTypes.length; i++) {
            Class<?> type = paramsTypes[i];
            if (type == HttpServletRequest.class || type == HttpServletResponse.class){
                paramIndexMapping.put(type.getName(), i);
            }
        }
    }
}
